<template>
  <div class="questionnaire-page" :key="pageKey">
    <div
      class="w-full h-1/3 flex justify-center items-center bg-black bg-opacity-60 text-white text-3xl pb-8"
    >
      {{ query["scene"] == "2" ? "直播已结束" : "课程已结束" }}
    </div>
    <Question
      v-if="!errMessage"
      class="w-full h-2/3 pb-2 z-20 overflow-y-auto question-list"
      style="height: 67vh"
      :isVisible="true"
      :questions="questionList"
      :answerTimeLimit="answerTimeLimit"
      @complete="onAnswerState(1)"
      @fail="onAnswerState(2)"
      @timeout="onTimeout"
    />
    <!-- :answerNum="answerNum"
      :answerCount="answerCount ?? 0" -->
    <div
      v-else
      class="w-full h-2/3 z-20 flex flex-col justify-center items-center text-gray-500 text-base"
    >
      {{ errMessage }}

      <button
        v-show="isShowRetry"
        @click="redirectToOriginal"
        class="w-2/3 mt-6 py-3.5 rounded-full bg-gradient-to-r from-blue-400 to-blue-500 text-white text-lg font-medium active:opacity-90 transition-all duration-300 shadow-lg shadow-blue-300/30 hover:shadow-blue-300/50 hover:scale-[1.02]"
      >
        重新学习
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { launchRedPacket3Times } from "@/store/useRedPacket";
import { useQuestionnaireStore } from "@/store/useQuestionnaireStore";
import { useCourseData } from "@/store/useCourse";
import useLiveDataStore from "@/views/LiveNew/stores/LiveDataStore";
import { isWeChatBrowserPro } from "@/utils/wechat";
// import Question from "@/views/LiveNew/components/Question.vue";
import Question from "./Question.vue";
import { showToast } from "vant";
import setPageTitle from "@/utils/set-page-title";
import dayjs from "dayjs";

const questionnaireStore = useQuestionnaireStore();

const query = useRoute().query;
const pageKey = ref(Date.now());
const errMessage = ref("暂无数据");
const isShowRetry = ref(false);
const answerTimeLimit = ref(0);
const questionList = ref([]);
const isTimeout = ref(false);
const router = useRouter();

const redirectToOriginal = () => {
  router.replace({
    name: query["scene"] == "2" ? "Live" : "Course",
    query: query
  });
};

const onTimeout = () => {
  isTimeout.value = true;
  errMessage.value = "答题时间已结束";
};

const updateStateMessage = pullState => {
  if (pullState == 3) {
    errMessage.value = "红包领取成功";
  } else if (pullState == 4 || pullState == 6) {
    errMessage.value = "红包未领取";
  } else if (pullState == 5 || pullState == 7) {
    errMessage.value = "收款失败";
  } else if (pullState == 2) {
    errMessage.value = "微信版本不支持红包功能";
  } else if (pullState == 1) {
    errMessage.value = "等待领取";
  }

  if (pullState != 1) {
    showToast(errMessage.value);
  }
};

const handleLaunchRedPacket = async (packageInfo, sn) => {
  const callback = pullState => {
    updateStateMessage(pullState);

    isShowRetry.value = true;
  };
  // 拉起红包
  launchRedPacket3Times({
    packageInfo,
    sn,
    sendPullState: questionnaireStore.sendPullState,
    callback
  });
};

const onAnswerState = async state => {
  // state 1 答题成功 2 答题失败
  errMessage.value = "提交中，请勿关闭！";
  const res = await questionnaireStore.postAnswerCompensation(state);
  if (state == 1) {
    if (res?.amount) {
      errMessage.value = "领取红包中，请勿关闭！";
      const {
        sn,
        packageInfo,
        message = "单据信息缺失，请稍后再试",
        bizCode
      } = await questionnaireStore.postRewardCompensation(
        questionnaireStore.roomParams.value
      );
      if (!packageInfo || !sn) {
        errMessage.value = message;
        showToast(message);
        return;
      }
      if (bizCode !== "SUCCESS") {
        errMessage.value = message;
        showToast(message);
        return;
      }
      // 拉起红包
      handleLaunchRedPacket(packageInfo, sn);
    } else {
      errMessage.value = `答题成功！`;

      isShowRetry.value = true;
    }
  } else {
    // 进入错误页面
    errMessage.value = `当前题目答错${questionnaireStore.totalAttempts}次，答题结束！`;

    isShowRetry.value = true;
  }
};

const onGameOver = resMsg => {
  router.replace({
    name: query["scene"] == "2" ? "LiveEnd" : "CourseError",
    query: { ...query, resultMsg: resMsg }
  });
};

const updateQsData = (res, title) => {
  const curPageTitle = res.shopName ?? res.title ?? title;
  setTimeout(() => {
    // setPageTitle(curPageTitle);
    document.title = curPageTitle;
  }, 30);

  errMessage.value = "";

  // isAnswer 是否回答,
  // 已经答题
  if (res?.isAnswer == 1) {
    // answerState 答题状态 1：答题正确、2：答题失败、3：超时未答题
    const answerStateData = {
      1: "您已经答题成功！",
      2: `当前题目答错${questionnaireStore.totalAttempts}次，答题结束！`,
      3: "超时未答题!"
    };
    errMessage.value = answerStateData[res.answerState] ?? "答题失败！";

    isShowRetry.value = true;
  }

  if (errMessage.value) return;

  // 未答题
  questionList.value = res.questionSettingVoList.filter(e => e.selected == 1);
  if (!questionList.value.length) {
    errMessage.value = "未获取到题目列表！";
  }
  // answerTimeLimit.value = res.openEndTime
  //   ? dayjs(res.openEndTime).diff(dayjs(), "second")
  //   : questionnaireStore.questionnaireInfo?.answerTimeLimit * 60;
  answerTimeLimit.value =
    questionnaireStore.questionnaireInfo?.answerTimeLimit * 60;

  isTimeout.value = res.openEndTime
    ? dayjs(res.openEndTime).isBefore(dayjs())
    : false;
};

const onEntryCheck = async () => {
  if (isWeChatBrowserPro()) {
    let checkRes = {};
    let title = "";
    if (query["scene"] == "2") {
      title = "直播";
      // 直播
      checkRes = await useLiveDataStore().checkEntrance();
    } else {
      title = "课程";
      // 课程
      checkRes = await useCourseData().checkInviteCode(query["inviteCode"]);
    }
    if (checkRes?.adjustmentParam) {
      const res = await questionnaireStore.getRoomWatchRecordByUserId(
        checkRes?.adjustmentParam
      );
      console.log("watch result res: ", res);
      if (res.result) {
        updateQsData(res, title);
      } else {
        isTimeout.value = true;
        errMessage.value = res.resMsg || "已结束";
        // if (res.resMsg) {
        //   onGameOver(res.resMsg);
        // }
      }
    }
  }
};

onBeforeMount(() => {
  pageKey.value = Date.now();
  isTimeout.value = false;
  errMessage.value = "暂无数据";

  onEntryCheck();
});
</script>

<style scoped>
.questionnaire-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f7f8fa;
}

.error-content {
  width: 80%;
  padding: 20px;
}

.question-list .bottom-0 {
  bottom: env(safe-area-inset-bottom);
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style>
